import requests
import edge_tts
import pyaudio,wave,sys
from pydub import AudioSegment
import tqdm
from pydub.playback import play
import numpy as np
from scipy.signal import wiener
# 打开音频文件
pa = pyaudio.PyAudio()
RATE=16000
CHUNK=1024
RECORD_SECONDS=5
# 打开声卡，设置 采样深度为16位、声道数为2、采样率为16K、输入、采样点缓存数量为2048
stream = pa.open(format=pyaudio.paInt16, channels=1, rate=RATE, input=True,frames_per_buffer=CHUNK)
# 新建一个列表，用来存储采样到的数据
# 定义去噪函数
def denoise_audio(audio_data, sample_rate, noise_scale=2):
    audio_data = np.frombuffer(audio_data, dtype=np.int16)
    audio_data = audio_data * 1.0 / max(abs(audio_data))
    Y = wiener(audio_data, mysize=sample_rate * noise_scale)
    return Y.astype(np.int16)
def play(strdd):
    VOICE = "zh-CN-shaanxi-XiaoniNeural"
    OUTPUT_FILE = "test.mp3"
    communicate = edge_tts.Communicate(strdd, VOICE)
    communicate.save_sync(OUTPUT_FILE)
    #song = AudioSegment.from_wav(OUTPUT_FILE)
    #play(song)
    import subprocess
     
    # 执行一个bash命令，例如列出当前目录下的文件
    command = "mpg123 test.mp3"
    process = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
def send(stream):
    moreDatas = []
    # 开始采样
    for i in range(int(RATE / CHUNK * RECORD_SECONDS)):          # 录音5秒
        sdata = stream.read(CHUNK)   # 读出声卡缓冲区的音频数据
        #audio_data = denoise_audio(sdata, RATE)
        audio_data=np.frombuffer(sdata,dtype=np.int16)
        moreDatas.append(audio_data)# 将读出的音频数据追加到record_buf列表
    # 发送POST请求
    if len(moreDatas)>3:
        moreDatas.pop(0)

    print(np.array(moreDatas).shape)
    newDatas=[i for j in moreDatas for i in j]
    buffers=b''
    for buffer in newDatas:
        buffers+=buffer
    buffers_data = denoise_audio(buffers, RATE)
    response=requests.post(url='http://192.168.50.191:5000/stream',data=buffers_data,stream=True)
    print(response.text)
    play(response.text)
    #play("你好，得到的灌水灌水")
while True:
    stream.start_stream()
    send(stream)
    stream.stop_stream()
# 输出响应内容
stream.close()